<template>
  <div class="role-management">
    <!-- 顶部标签页 -->
    <div class="tabs-container">
      <div 
        v-for="tab in tabs" 
        :key="tab.key"
        :class="['tab-item', { active: activeTab === tab.key }]"
        @click="activeTab = tab.key"
      >
        {{ tab.label }}
      </div>
    </div>

    <!-- 功能说明和新建角色按钮 -->
    <div class="action-bar">
      <div class="description">
        新建角色，通过建立不同的角色，赋予对应的权限，高效地进行权限管理
      </div>
      <el-button type="primary" @click="handleCreateRole">
        新建角色
      </el-button>
    </div>

    <!-- 角色列表 -->
    <div class="role-list">
      <el-table :data="roleData" style="width: 100%" v-loading="loading">
        <el-table-column prop="username" label="账号" width="200" />
        <el-table-column prop="name" label="名称" width="200" />
        <el-table-column label="操作" width="300" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleSetPermission(scope.row)">
              角色权限
            </el-button>
            <el-button type="success" size="small" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="userType" label="角色类型" width="120" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新建/编辑角色对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form :model="roleForm" :rules="roleRules" ref="roleFormRef" label-width="100px">
        <el-form-item label="账号" prop="username">
          <el-input v-model="roleForm.username" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色类型" prop="userType">
          <el-select v-model="roleForm.userType" placeholder="请选择角色类型" style="width: 100%">
            <el-option label="管理员" value="管理员" />
            <el-option label="普通用户" value="普通用户" />
            <el-option label="测试角色" value="测试角色" />
            <el-option label="测试权限" value="测试权限" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="roleForm.description" 
            type="textarea" 
            rows="3"
            placeholder="请输入角色描述" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 权限设置对话框 -->
    <el-dialog v-model="permissionDialogVisible" title="角色权限设置" width="600px">
      <div class="permission-content">
        <el-tree
          ref="permissionTreeRef"
          :data="permissionData"
          :props="treeProps"
          show-checkbox
          node-key="id"
          :default-checked-keys="checkedPermissions"
          @check="handlePermissionCheck"
        />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSavePermissions">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const permissionDialogVisible = ref(false)
const activeTab = ref('role')
const roleFormRef = ref()
const permissionTreeRef = ref()
const editingRole = ref(null)
const checkedPermissions = ref([])

// 标签页数据
const tabs = [
  { key: 'role', label: '角色管理' },
  { key: 'account', label: '账户管理' }
]

// 对话框标题
const dialogTitle = computed(() => {
  return editingRole.value ? '编辑角色' : '新建角色'
})

// 角色表单
const roleForm = reactive({
  username: '',
  name: '',
  userType: '',
  description: ''
})

// 表单验证规则
const roleRules = {
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' }
  ],
  userType: [
    { required: true, message: '请选择角色类型', trigger: 'change' }
  ]
}

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 角色数据
const roleData = ref([
  {
    id: 1,
    username: 'weiuAdmin',
    name: '管理员',
    description: '',
    userType: '管理员',
    createTime: '2023-05-15 00:56:25'
  },
  {
    id: 2,
    username: 'HRD',
    name: 'HRD',
    description: '',
    userType: '普通用户',
    createTime: '2023-05-15 01:03:04'
  },
  {
    id: 3,
    username: 'HR-Manager',
    name: 'HR-Manager',
    description: '',
    userType: '普通用户',
    createTime: '2023-05-15 09:29:49'
  },
  {
    id: 4,
    username: 'test22',
    name: 'test',
    description: '测试角色',
    userType: '普通用户',
    createTime: '2024-01-08 09:31:22'
  },
  {
    id: 5,
    username: 'test',
    name: 'Test',
    description: '测试权限',
    userType: '普通用户',
    createTime: '2024-04-03 09:48:05'
  }
])

// 权限树数据
const permissionData = ref([
  {
    id: 1,
    label: '权限管理',
    children: [
      { id: 11, label: '角色管理' },
      { id: 12, label: '账号管理' }
    ]
  },
  {
    id: 2,
    label: '组织管理',
    children: [
      { id: 21, label: '部门管理' },
      { id: 22, label: '人员管理' }
    ]
  },
  {
    id: 3,
    label: '团队测评',
    children: [
      { id: 31, label: '项目团队' },
      { id: 32, label: '测评入口' },
      { id: 33, label: '查询报告' }
    ]
  }
])

const treeProps = {
  children: 'children',
  label: 'label'
}

// 方法
const handleCreateRole = () => {
  editingRole.value = null
  dialogVisible.value = true
  // 重置表单
  Object.assign(roleForm, {
    username: '',
    name: '',
    userType: '',
    description: ''
  })
}

const handleEdit = (row) => {
  editingRole.value = row
  dialogVisible.value = true
  // 填充表单数据
  Object.assign(roleForm, {
    username: row.username,
    name: row.name,
    userType: row.userType,
    description: row.description
  })
}

const handleSubmit = async () => {
  try {
    await roleFormRef.value.validate()
    
    if (editingRole.value) {
      // 编辑角色
      const index = roleData.value.findIndex(item => item.id === editingRole.value.id)
      if (index > -1) {
        Object.assign(roleData.value[index], roleForm)
        ElMessage.success('角色更新成功')
      }
    } else {
      // 新建角色
      const newRole = {
        id: Date.now(),
        username: roleForm.username,
        name: roleForm.name,
        userType: roleForm.userType,
        description: roleForm.description,
        createTime: new Date().toLocaleString('zh-CN')
      }
      roleData.value.unshift(newRole)
      pagination.total++
      ElMessage.success('角色创建成功')
    }
    
    dialogVisible.value = false
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

const handleSetPermission = (row) => {
  editingRole.value = row
  permissionDialogVisible.value = true
  // 模拟加载该角色的权限
  checkedPermissions.value = [11, 21, 31] // 示例权限
}

const handlePermissionCheck = (data, checked) => {
  console.log('权限变更:', data, checked)
}

const handleSavePermissions = () => {
  const checkedKeys = permissionTreeRef.value.getCheckedKeys()
  console.log('保存权限:', checkedKeys)
  ElMessage.success('权限设置成功')
  permissionDialogVisible.value = false
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除角色"${row.name}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const index = roleData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      roleData.value.splice(index, 1)
      pagination.total--
      ElMessage.success('删除成功')
    }
  } catch {
    // 用户取消删除
  }
}

const handleSizeChange = (val) => {
  pagination.pageSize = val
  loadRoleData()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  loadRoleData()
}

const loadRoleData = () => {
  loading.value = true
  setTimeout(() => {
    pagination.total = roleData.value.length
    loading.value = false
  }, 500)
}

onMounted(() => {
  loadRoleData()
})
</script>

<style scoped>
.role-management {
  background: white;
  border-radius: 8px;
  padding: 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.tabs-container {
  display: flex;
  border-bottom: 1px solid #e5e7eb;
  background: white;
  border-radius: 8px 8px 0 0;
}

.tab-item {
  padding: 16px 32px;
  cursor: pointer;
  color: #6b7280;
  font-weight: 500;
  border-bottom: 3px solid transparent;
  transition: all 0.3s;
  position: relative;
}

.tab-item:first-child {
  border-radius: 8px 0 0 0;
}

.tab-item.active {
  color: white;
  background: #5a67d8;
  border-bottom-color: #5a67d8;
}

.tab-item:hover:not(.active) {
  background: #f3f4f6;
  color: #374151;
}

.action-bar {
  padding: 20px 24px;
  background: #f8fafc;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.description {
  color: #6b7280;
  font-size: 14px;
}

.role-list {
  padding: 24px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid #e5e7eb;
}

.permission-content {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  padding: 16px;
}

:deep(.el-table th) {
  background: #f8fafc !important;
  color: #374151;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 16px 0;
}

:deep(.el-button + .el-button) {
  margin-left: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-tree-node__content) {
  padding: 8px 0;
  font-size: 14px;
}

:deep(.el-tree-node__label) {
  font-size: 14px;
  color: #374151;
}
</style>
